use std::fmt::Debug;

use anyhow::bail;
use serde::Serialize;

use util::json_to_dto;

use crate::common::CommResult;
use crate::config::get_hclient;
use crate::dto::base_dto::{BizDto, ResDto};
use crate::dto::biz_code;
use crate::dto::sys_dto::HostDto;
use crate::dto::task::BatchTaskInfo;
use crate::util;

/// 心跳获取下发任务
pub fn fetch_msg_task() -> BatchTaskInfo {
    let mut bti = BatchTaskInfo::default();
    bti.task_list = post("/fetch-msg", biz_code::HEART_BEAT, &String::new())
        .and_then(|resdto| {
            let data: Vec<BizDto> = json_to_dto(&resdto.data).unwrap_or_default();
            let msgid = resdto.msg_id;
            bti.msg_id = msgid.clone();
            Some(data)
        });
    bti
}

/// 注册主机
pub fn reg_host(dto: HostDto) -> CommResult<String> {
    if let Some(res) = post("/reg-host", biz_code::REG_HOST, &dto) {
        Ok(res.msg)
    } else {
        bail!("主机注册失败.")
    }
}

pub fn post<T: ?Sized + Serialize + 'static + Debug>(path: &str, biz_code: u32, dto: &T) -> Option<ResDto> {
    get_hclient().map_or(None, |client| client.post(path, biz_code, dto)
        .map_or(None, |res| Some(res)))
}

pub fn post_common<T: ?Sized + Serialize + 'static + Debug>(msg_id: String, biz_code: u32, dto: &T) -> Option<ResDto> {
    get_hclient().map_or(None, |client|
        client.post_res("/common-msg", msg_id, biz_code, dto)
            .map_or(None, |res| Some(res)))
}

pub fn post_common_rt<T: ?Sized + Serialize + 'static + Debug>(msg_id: String, biz_code: u32, dto: &T) -> CommResult<ResDto> {
    if let Ok(client) = get_hclient() {
        client.post_res("/common-msg", msg_id, biz_code, dto)
    } else {
        bail!("获取httpclient失败")
    }
}
